<?php
namespace app\index\controller;

use think\Controller;
use think\facade\Cookie;
use think\facade\Session;

class Wechat extends Controller
{

    protected $appid;
    protected $appsecret;

    public function __construct()
    {
        $config = config('wechat.official_account');
        $this->appid = $config['appid'];
        $this->appsecret = $config['appsecret'];
    }

    /**
     * @param $redirect_url
     * @param $state
     */
    public function oauth($redirect_url,$state){
        $encodeUrl = urlencode($redirect_url);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$encodeUrl}&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";
        $this->redirect($url);
    }

    /**
     * @param $code
     * @return |null
     */
    public function getAccessToken($code){
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appsecret}&code={$code}&grant_type=authorization_code";
        $res = file_get_contents($url); //获取文件内容或获取网络请求的内容
        $data = json_decode($res,true);
        if(isset($data['errcode'])){
            return null;
        }
        return $data;
    }

    /**
     * @param $access_token
     * @param $openid
     * @return mixed
     */
    public function getWeChatUserInfo($access_token, $openid){
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        $output = file_get_contents($url);
        $wechatUserInfo = json_decode($output,true);
        $wechatUserInfo['cacheTime'] = time();
        session('wx_user_info', $wechatUserInfo);
        return $wechatUserInfo;
    }

}
